<?php

namespace plugin\admin\app\controller;

use app\service\CarQrcodeService;
use support\Request;
use support\Response;
use plugin\admin\app\model\Agent;
use support\exception\BusinessException;

/**
 * 代理管理
 */
class AgentController extends Crud
{

    /**
     * @var Agent
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Agent;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('agent/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            //新增数量
            $count = $request->post('count', 1);

            $data = [];

            for ($i = 0; $i < $count; $i++) {
                $data[] = [
                    'user_id' => null,
                ];
            }

            Agent::insert($data);
            return $this->json(0);
        }
        return view('agent/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('agent/update');
    }

    //生成小程序码
    public function generate(Request $request): Response
    {
        $primary_key = $this->model->getKeyName();
        if (!$primary_key) {
            throw new BusinessException('该表无主键，不支持操作');
        }
        $ids = (array)$request->post($primary_key, []);
        $this->doGenerate($ids);
        return $this->json(0);
    }

    /**
     * 执行生成
     * @param array $ids
     * @return void
     */
    protected function doGenerate(array $ids)
    {
        if (!$ids) {
            return;
        }
        $primary_key = $this->model->getKeyName();
        $this->model->whereIn($primary_key, $ids)->each(function ($model) {
            (new CarQrcodeService())->create_agent_qrcode($model->id);
        });
    }

    //下载图片
    public function download(Request $request): Response
    {
        $primary_key = $this->model->getKeyName();
        if (!$primary_key) {
            throw new BusinessException('该表无主键，不支持操作');
        }
        $ids = (array)$request->post($primary_key, []);
        // ✅ return 出下载响应
        return $this->doDownload($ids);
    }

    protected function doDownload(array $ids)
    {
        if (empty($ids)) {
            throw new BusinessException('未提供图片 ID');
        }

        $primary_key = $this->model->getKeyName();
        $images = $this->model->whereIn($primary_key, $ids)->pluck('img')->toArray();

        if (empty($images)) {
            throw new BusinessException('没有找到图片');
        }

        $zipPath = public_path() . '/images_' . date('Ymd_His') . '.zip';
        $zip = new \ZipArchive();

        if ($zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
            throw new BusinessException('无法创建压缩文件');
        }

        foreach ($images as $image) {
            $filePath = public_path() . '/' . ltrim($image, '/');

            if (!is_file($filePath)) {
                // 如果找不到文件可以跳过或抛出异常
                continue; // 或 throw new BusinessException("找不到文件：{$filePath}");
            }

            $relativeName = basename($filePath);
            $success = $zip->addFile($filePath, $relativeName);

            if (!$success) {
                throw new BusinessException("添加文件失败：{$filePath}");
            }
        }

        $zip->close();

        // 自动删除 zip 文件
        $response = response()->download($zipPath, basename($zipPath))->withHeaders([
            'Content-Type' => 'application/zip',
        ]);


        register_shutdown_function(function () use ($zipPath) {
            if (file_exists($zipPath)) {
                unlink($zipPath);
            }
        });

        return $response;
    }

}
